package com.chart.web.controller.chart;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.beust.jcommander.Strings;
import com.chart.chart.domian.ChartViewsUser;
import com.chart.chart.domian.vo.CharIdsVO;
import com.chart.chart.domian.vo.ChartViewsUserPasswordVO;
import com.chart.chart.domian.vo.ChartViewsUserVO;
import com.chart.chart.domian.vo.ChartViewsVo;
import com.chart.chart.service.IChartConfigsService;
import com.chart.chart.service.IChartViewsThemeService;
import com.chart.chart.service.IChartViewsUserService;
import com.chart.common.constant.CacheConstants;
import com.chart.common.constant.Constants;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.page.TableDataInfo;
import com.chart.common.core.redis.RedisCache;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.StringUtils;
import com.chart.common.utils.uuid.IdUtils;
import com.chart.framework.config.OssConfig;
import com.chart.framework.config.RedisConfig;
import com.chart.framework.config.ServerConfig;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.impl.SysUserServiceImpl;
import com.chart.web.controller.chart.dto.CharIdsDTO;
import com.chart.web.controller.chart.dto.ChartViewsDTO;
import com.example.entity.ChartViewsTheme;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.lettuce.core.cluster.RedisClusterURIUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static javax.crypto.Cipher.SECRET_KEY;

/**
 * 图表大屏
 *
 * @author chart
 */
@Slf4j
@RestController
@RequestMapping("/view/chart")
public class ChartViewsController extends BaseController {

    @Value("${phtoto.viewPhotoUrl}")
    private String viewPhotoUrl;

    @Value("${phtoto.photoUrl}")
    private String photoUrl;

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private RedisTemplate redisTemplate; // 注入 Redis 工具类

    @Autowired
    private IChartViewsUserService chartViewsUserService;

    @Autowired
    private IChartConfigsService chartConfigsService;

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IChartViewsThemeService chartViewsThemeService;

    @ApiOperation("数字大屏：列表")
    @Transactional
    @PostMapping("/user/list")
    public TableDataInfo list(@RequestBody ChartViewsVo chartViewsVo) {
        chartViewsVo.setUserId(SecurityUtils.getUserId());
        List<ChartViewsVo> list = chartViewsUserService.getList(chartViewsVo);
        return getDataTable(list);
    }


    /**
     * 根据id查询大屏
     * 要求返回密码
     *
     * @param id
     * @return
     */
    @GetMapping("/queryChartViewById")
    public AjaxResult queryChartViewById(Long id, String token) {

        ChartViewsUserVO chartViewsUser = chartViewsUserService.queryChartViewById(id);
        return AjaxResult.success(chartViewsUser);
    }


    /**
     * 复制的接口返回密码
     *
     * @param id
     * @return
     */
    @GetMapping("/queryChartViewPasswordById")
    public AjaxResult queryChartViewPasswordById(Long id) {
        ChartViewsUserPasswordVO chartViewsUser = chartViewsUserService.queryChartViewPasswordById(id);
        return AjaxResult.success(chartViewsUser);
    }


    /**
     * 根据大屏id查询这个用户是不是VIP
     *
     * @param id
     * @return
     */
    @GetMapping("/queryUserVipByChartViewId")
    public AjaxResult queryUserVipByChartViewId(Long id) {
        if (id.equals("") || id == null) {
            return AjaxResult.error(400, "id为空请重试");
        }
        ChartViewsUserVO chartViewsUser = chartViewsUserService.queryChartViewById(id);
        //查询用户user_id
        Long userId = chartViewsUser.getUserId();
        if (userId.equals("") || userId == null) {
            return AjaxResult.error(521, "该id未查到到userId");
        }
        Integer str = sysUserService.queryByUserId(userId);
        chartViewsUser.setIsVip(str);


        return AjaxResult.success(chartViewsUser);
    }


    /**
     * 根据保存的我的生成id和大屏id查询集合
     */
    @PostMapping("chartConfigsUserAndChartViewsUser")
    public AjaxResult chartConfigsUserAndChartViewsUser(@RequestBody CharIdsDTO charIdsDTO) {

        List<Long> configIds = charIdsDTO.getConfigIds();
        if (configIds.isEmpty()) {
            return new AjaxResult(620, "configIds为空，请重试！");

        }
        Long viewId = charIdsDTO.getViewId();
        if (viewId == null) {
            return new AjaxResult(621, "viewId为空，请重试！");
        }

        CharIdsVO charIdsVO = chartConfigsService.chartConfigsUserAndChartViewsUser(configIds, viewId);
        return AjaxResult.success(charIdsVO);
    }

    private static String generateRandomNumber(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 生成0到9之间的随机数字
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }


    @ApiOperation("数字大屏：新增")
    @PostMapping("/user/add")
    @Transactional
    public AjaxResult add(@RequestBody ChartViewsUser chartViewsUser) {


        Integer viewsThemeId = chartViewsUser.getViewsThemeId();

        if(viewsThemeId==null||viewsThemeId.equals("")){
            return AjaxResult.error(400, "viewsThemeId为空，请重试");
        }
        // 查询 viewsThemeId 是否存在
        ChartViewsTheme viewsTheme = chartViewsThemeService.getById(viewsThemeId);
        if (viewsTheme == null) {
            return AjaxResult.error(404, "viewsThemeId 对应的记录不存在，请检查后重试");
        }

        chartViewsUser.setViewsThemeId(viewsThemeId);
        //查询用户id
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return AjaxResult.error(650, "获取用户id失败");
        }

        chartViewsUser.setUserId(userId);
        // 查询SysUser对象
        SysUser sysUser = sysUserService.selectUserById(userId);
        if (ObjectUtils.isEmpty(sysUser)) {
            return AjaxResult.error(651, "为查询到该对象");
        }

        // 获取isVip字段并校验
        Integer isVip = sysUser.getIsVip();


        if (StringUtils.isEmpty(chartViewsUser.getViewName())) {
            String randomNumber = generateRandomNumber(6); // 生成6位随机数字
            String name = "临时" + randomNumber;
            chartViewsUser.setViewName(name);
        }


        //不是会员 一个用户只能保存一个大屏
        if (isVip != 1) {
            LambdaQueryWrapper<ChartViewsUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChartViewsUser::getUserId, userId);
            wrapper.isNull(ChartViewsUser::getDeleteTime); // 添加 delete_time IS NULL 条件
            List<ChartViewsUser> list = chartViewsUserService.list(wrapper);
            if (list.size() > 0) {
                return AjaxResult.error(653,"非会员用户只能保存一个大屏");
            }

            // 获取当前日期并格式化为 "yyMMdd"
            String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
            // 生成随机数字并进行 MD5 加密
            String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
            String md5FileName = generateMD5(randomNumber);
            // 构造文件路径：chartCover/241209/md5(XXXX).png
            String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
            if (!chartViewsUser.getBase64Data().isEmpty()) {
                // 解码 Base64 图表封面
                byte[] decodedBytes = decodeBase64Image(chartViewsUser.getBase64Data());
                // 上传文件到 OSS
                OSS ossClient = null;
                String fileUrl = null;  // 保存到OSS后的文件 URL
                String base64Encoded = null;
                try {
                    ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                            ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                    ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(decodedBytes));

                    // 设置文件权限为公共读
                    ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

                    // 构造 OSS 文件 URL
                    if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                        fileUrl = ossConfig.getCustomDomain() + "/" + fileName;
                    } else {
                        fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                    }
                } catch (IllegalArgumentException e) {
                    log.error("Base64解码失败或上传OSS异常", e);
                    // 如果Base64字符串非法或无法解码，则捕获此异常并返回错误消息
                    return AjaxResult.error("Base64解码失败: " + e.getMessage());
                } finally {
                    if (ossClient != null) {
                        ossClient.shutdown();  // 确保资源被释放
                    }
                }
                chartViewsUser.setLargeScreenUrl(fileUrl);
            }

            boolean result = chartViewsUserService.save(chartViewsUser);
            if (result) {
                return AjaxResult.success(chartViewsUser.getId());
            }
            return AjaxResult.error();


        }


        chartViewsUser.setUserId(SecurityUtils.getUserId());

        if (!StringUtils.isEmpty(chartViewsUser.getImageUrl())) {
            chartViewsUser.setImageUrl(chartViewsUser.getImageUrl());
        }

        if (StringUtils.isEmpty(chartViewsUser.getBase64Data())) {
            return AjaxResult.error("base64Data为空，请重试！");
        }


        // 获取当前日期并格式化为 "yyMMdd"
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 生成随机数字并进行 MD5 加密
        String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
        String md5FileName = generateMD5(randomNumber);
        // 构造文件路径：chartCover/241209/md5(XXXX).png
        String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
        if (!chartViewsUser.getBase64Data().isEmpty()) {
            // 解码 Base64 图表封面
            byte[] decodedBytes = decodeBase64Image(chartViewsUser.getBase64Data());
            // 上传文件到 OSS
            OSS ossClient = null;
            String fileUrl = null;  // 保存到OSS后的文件 URL
            String base64Encoded = null;
            try {
                ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(decodedBytes));

                // 设置文件权限为公共读
                ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

                // 构造 OSS 文件 URL
                if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                    fileUrl = ossConfig.getCustomDomain() + "/" + fileName;
                } else {
                    fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                }
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败或上传OSS异常", e);
                // 如果Base64字符串非法或无法解码，则捕获此异常并返回错误消息
                return AjaxResult.error("Base64解码失败: " + e.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();  // 确保资源被释放
                }
            }
            chartViewsUser.setLargeScreenUrl(fileUrl);
        }

        boolean result = chartViewsUserService.save(chartViewsUser);
        if (result) {
            return AjaxResult.success(chartViewsUser.getId());
        }
        return AjaxResult.error();
    }







/*
    @ApiOperation("数字大屏：修改")
    @PutMapping("/user/update")
    @Transactional
    public AjaxResult update(@RequestBody ChartViewsUser chartViewsUser) {




        if (StringUtils.isEmpty(chartViewsUser.getBase64Data())) {
            return AjaxResult.error(400,"base64Data为空，请重试！");
        }
        if (StringUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error(400,"viewName为空，请重试！");
        }

        if(chartViewsUser.getId().equals("")||chartViewsUser==null){
            return AjaxResult.error(400,"id为空，请重试！");
        }


            chartViewsUser.setViewName(chartViewsUser.getViewName());
               chartViewsUser.setUserId(SecurityUtils.getUserId());

        if (!StringUtils.isEmpty(chartViewsUser.getImageUrl())) {
            chartViewsUser.setImageUrl(chartViewsUser.getImageUrl());
        }



        // 获取当前日期并格式化为 "yyMMdd"
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 生成随机数字并进行 MD5 加密
        String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
        String md5FileName = generateMD5(randomNumber);
        // 构造文件路径：chartCover/241209/md5(XXXX).png
        String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
        if (!chartViewsUser.getBase64Data().isEmpty()) {
            // 解码 Base64 图表封面
            byte[] decodedBytes = decodeBase64Image(chartViewsUser.getBase64Data());
            // 上传文件到 OSS
            OSS ossClient = null;
            String fileUrl = null;  // 保存到OSS后的文件 URL
            String base64Encoded = null;
            try {
                ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(decodedBytes));

                // 设置文件权限为公共读
                ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

                // 构造 OSS 文件 URL
                if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                    fileUrl = ossConfig.getCustomDomain() + "/" + fileName;
                } else {
                    fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                }
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败或上传OSS异常", e);
                // 如果Base64字符串非法或无法解码，则捕获此异常并返回错误消息
                return AjaxResult.error("Base64解码失败: " + e.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();  // 确保资源被释放
                }
            }
            chartViewsUser.setLargeScreenUrl(fileUrl);
        }

        boolean result = chartViewsUserService.save(chartViewsUser);
        if (result) {
            return AjaxResult.success(chartViewsUser.getId());
        }
        return AjaxResult.error();
    }

*/

    /**
     * 删除大屏
     *
     * @param chartViewsUser
     * @return
     */

    @ApiOperation("数字大屏：软删除")
    @PostMapping("/user/delete")
    @Transactional
    public AjaxResult delete(@RequestBody ChartViewsUser chartViewsUser) {
        // 参数校验
        if (chartViewsUser == null || ObjectUtils.isEmpty(chartViewsUser.getId())) {
            return AjaxResult.error(400, "id为空，请重试！");
        }

        // 检查是否存在该ID对应的记录
        ChartViewsUser existingRecord = chartViewsUserService.getById(chartViewsUser.getId());
        if (existingRecord == null) {
            return AjaxResult.error(400, "未找到对应的大屏信息");
        }

        // 设置 delete_time 为当前时间，执行更新操作
        ChartViewsUser updateEntity = new ChartViewsUser();
        updateEntity.setId(chartViewsUser.getId());
        updateEntity.setDeleteTime(new Date()); // 设置当前时间为删除时间

        boolean result = chartViewsUserService.updateById(updateEntity);
        if (result) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }



    @ApiOperation("数字大屏：修改")
    @PostMapping("/user/update")
    @Transactional
    public AjaxResult update(@RequestBody ChartViewsUser chartViewsUser) {
        // 参数校验
        if (chartViewsUser == null || ObjectUtils.isEmpty(chartViewsUser.getId())) {
            return AjaxResult.error(400, "id为空，请重试！");
        }


        // 检查是否存在该ID对应的记录
        ChartViewsUser existingRecord = chartViewsUserService.getById(chartViewsUser.getId());
        if (existingRecord == null) {
            return AjaxResult.error(400, "未找到对应的大屏信息");
        }

        if (!StringUtils.isEmpty(chartViewsUser.getImageUrl())) {
            existingRecord.setImageUrl(chartViewsUser.getImageUrl());
        }

        // 更新非空字段
        BeanUtil.copyProperties(chartViewsUser, existingRecord, CopyOptions.create().ignoreNullValue());

        // 如果有新的base64Data，则更新封面图片
        if (!StringUtils.isEmpty(chartViewsUser.getBase64Data())) {
            try {
                String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
                String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
                String md5FileName = generateMD5(randomNumber);
                String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
                byte[] decodedBytes = decodeBase64Image(chartViewsUser.getBase64Data());
                OSS ossClient = new OSSClientBuilder().build(
                        ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(),
                        ossConfig.getAccessKeySecret()
                );

                ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(decodedBytes));
                ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

                String fileUrl;
                if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                    fileUrl = ossConfig.getCustomDomain() + "/" + fileName;
                } else {
                    fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                }
                existingRecord.setLargeScreenUrl(fileUrl);
                ossClient.shutdown();
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败或上传OSS异常", e);
                return AjaxResult.error("Base64解码失败: " + e.getMessage());
            }
        }

        // 执行更新操作
        boolean result = chartViewsUserService.updateById(existingRecord);
        if (result) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败");
    }


    @ApiOperation("数字大屏：修改")
    @PostMapping("/user/updateViewById")
    @Transactional
    public AjaxResult updateViewById(@RequestBody ChartViewsDTO chartViewsDTO) {


//        Integer viewsThemeId = chartViewsDTO.getViewsThemeId();
//        if(viewsThemeId==null||viewsThemeId.equals("")){
//            return AjaxResult.error(400, "viewsThemeId为空，请重试");
//        }
//       // 查询 viewsThemeId 是否存在
//        ChartViewsTheme viewsTheme = chartViewsThemeService.getById(viewsThemeId);
//        if (viewsTheme == null) {
//            return AjaxResult.error(404, "viewsThemeId 对应的记录不存在，请检查后重试");
//        }



        Long id = chartViewsDTO.getId();
        Integer openShare = chartViewsDTO.getOpenShare();
        Integer accessCheck = chartViewsDTO.getAccessCheck();
        String password = chartViewsDTO.getPassword();
        return chartViewsUserService.updateViewById(id, openShare, accessCheck, password);
    }




/*
    @ApiOperation("数字大屏：新增")
    @PostMapping("/user/addBase64")
    @Transactional
    public AjaxResult addBase64(@RequestBody ChartViewsUser chartViewsUser) {
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写大屏名称");
        }

        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>()
                .eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()));

        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error(400,"大屏名称重复");
        }
        if(StringUtils.isEmpty(chartViewsUser.getImageUrl())){
            return AjaxResult.error(400,"imageUrl为空，请重试！");
        }
        if(StringUtils.isEmpty(chartViewsUser.getLargeScreenUrl())){
            return AjaxResult.error(400,"largeScreenUrl为空，请重试！");
        }


        chartViewsUser.setUserId(SecurityUtils.getUserId());


        // 获取当前日期并格式化为 "yyMMdd"
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 生成随机数字并进行 MD5 加密
        String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
        String md5FileName = generateMD5(randomNumber);
        // 构造文件路径：chartCover/241209/md5(XXXX).png
        String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
        String fileName2 = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
        if (!chartViewsUser.getImageUrl().isEmpty()) {


            // 解码 Base64 图表封面
            byte[] decodedBytes = decodeBase64Image(chartViewsUser.getImageUrl());
            // 上传文件到 OSS
            OSS ossClient = null;
            String fileUrl = null;  // 保存到OSS后的文件 URL
            String base64Encoded = null;
            try {
                ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(decodedBytes));

                // 设置文件权限为公共读
                ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

                // 构造 OSS 文件 URL
                if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                    fileUrl = ossConfig.getCustomDomain() + "/" + fileName;
                } else {
                    fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
                }
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败或上传OSS异常", e);
                // 如果Base64字符串非法或无法解码，则捕获此异常并返回错误消息
                return AjaxResult.error("Base64解码失败: " + e.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();  // 确保资源被释放
                }
            }
            chartViewsUser.setImageUrl(fileUrl);
        }



        if (!chartViewsUser.getLargeScreenUrl().isEmpty()) {
            // 解码 Base64 图表封面
            byte[] decodedBytes = decodeBase64Image(chartViewsUser.getLargeScreenUrl());
            // 上传文件到 OSS
            OSS ossClient = null;
            String fileUrl1 = null;  // 保存到OSS后的文件 URL
            String base64Encoded = null;
            try {
                ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                ossClient.putObject(ossConfig.getBucketName(), fileName2, new ByteArrayInputStream(decodedBytes));

                // 设置文件权限为公共读
                ossClient.setObjectAcl(ossConfig.getBucketName(), fileName2, CannedAccessControlList.PublicRead);

                // 构造 OSS 文件 URL
                if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                    fileUrl1 = ossConfig.getCustomDomain() + "/" + fileName2;
                } else {
                    fileUrl1 = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName2;
                }
            } catch (IllegalArgumentException e) {
                log.error("Base64解码失败或上传OSS异常", e);
                // 如果Base64字符串非法或无法解码，则捕获此异常并返回错误消息
                return AjaxResult.error("Base64解码失败: " + e.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();  // 确保资源被释放
                }
            }
            chartViewsUser.setLargeScreenUrl(fileUrl1);
        }
        boolean result = chartViewsUserService.save(chartViewsUser);
        if (result) {
            return AjaxResult.success(chartViewsUser.getId());
        }
        return AjaxResult.error();
    }
*/


    @ApiOperation("数字大屏：新增")
    @PostMapping("/user/addBase64")
    @Transactional
    public AjaxResult addBase64(@RequestBody ChartViewsUser chartViewsUser) {
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写大屏名称");
        }

        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>()
                .eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()));

        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error(400, "大屏名称重复");
        }
        if (StringUtils.isEmpty(chartViewsUser.getImageUrl()) || StringUtils.isEmpty(chartViewsUser.getLargeScreenUrl())) {
            return AjaxResult.error(400, "base64为空，请重试！");
        }
        chartViewsUser.setUserId(SecurityUtils.getUserId());
        // 获取当前日期并格式化为 "yyMMdd"
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 构造文件路径：largeScreen/241209/md5(XXXX).jpg
        String imageFilePath = generateUniqueFilePath(datePrefix, "image");
        String largeScreenFilePath = generateUniqueFilePath(datePrefix, "largeScreen");
        try {
            // 处理 imageUrl
            String fileUrl = uploadToOSS(imageFilePath, chartViewsUser.getImageUrl());
            chartViewsUser.setImageUrl(fileUrl);

            // 处理 largeScreenUrl
            String fileUrl1 = uploadToOSS(largeScreenFilePath, chartViewsUser.getLargeScreenUrl());
            chartViewsUser.setLargeScreenUrl(fileUrl1);

            boolean result = chartViewsUserService.save(chartViewsUser);
            if (result) {
                return AjaxResult.success(chartViewsUser.getId());
            } else {
                return AjaxResult.error();
            }
        } catch (IllegalArgumentException e) {
            log.error("Base64解码失败或上传OSS异常", e);
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

    private String generateUniqueFilePath(String datePrefix, String type) {
        // 生成随机数字并进行 MD5 加密，加上类型以保证唯一性
        String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
        String md5FileName = generateMD5(randomNumber + type);
        return "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";
    }

    private String uploadToOSS(String filePath, String base64String) throws IllegalArgumentException {
        byte[] decodedBytes = decodeBase64Image(base64String);

        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(
                    ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret()
            );
            ossClient.putObject(ossConfig.getBucketName(), filePath, new ByteArrayInputStream(decodedBytes));

            // 设置文件权限为公共读
            ossClient.setObjectAcl(ossConfig.getBucketName(), filePath, CannedAccessControlList.PublicRead);

            // 构造 OSS 文件 URL
            String fileUrl;
            if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                fileUrl = ossConfig.getCustomDomain() + "/" + filePath;
            } else {
                fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + filePath;
            }
            return fileUrl;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();  // 确保资源被释放
            }
        }
    }


    @ApiOperation("数字大屏：新增")
    @PostMapping("/user/add/largeScreenFile")
    @Transactional
    public AjaxResult addFile(
            @RequestPart(value = "chartViewsUser", required = true) ChartViewsUser chartViewsUser,
            @RequestPart(value = "file1", required = false) MultipartFile file1,
            @RequestPart(value = "file2", required = false) MultipartFile file2) throws IOException {

        byte[] bytes1 = file1.getBytes();
        byte[] bytes2 = file2.getBytes();
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写大屏名称");
        }
        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()));

        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("大屏名称重复");
        }
        chartViewsUser.setUserId(SecurityUtils.getUserId());


        // 获取当前日期并格式化为 "yyMMdd"
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 生成随机数字并进行 MD5 加密
        String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
        String md5FileName = generateMD5(randomNumber);
        // 构造文件路径：chartCover/241209/md5(XXXX).png
        String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".jpg";

        String fileUrl1 = null;
        OSS ossClient = null;
        try {

            ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

            // 上传文件
            ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(bytes1));
            // 设置文件权限为公共读
            ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

            // 构造文件访问 URL
            if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                fileUrl1 = ossConfig.getCustomDomain() + fileName;
            } else {
                fileUrl1 = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
            }
        } catch (OSSException e) {
            log.error("文件1上传到 OSS 失败", e);
            return AjaxResult.error("文件上传失败");
        } catch (ClientException e) {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


        //上传第二张照片
        String fileUrl2 = null;
        OSS ossClient2 = null;
        try {

            ossClient2 = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

            // 上传文件
            ossClient2.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(bytes2));
            // 设置文件权限为公共读
            ossClient2.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

            // 构造文件访问 URL
            if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                fileUrl2 = ossConfig.getCustomDomain() + fileName;
            } else {
                fileUrl2 = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
            }
        } catch (OSSException e) {
            log.error("文件1上传到 OSS 失败", e);
            return AjaxResult.error("文件上传失败");
        } catch (ClientException e) {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        chartViewsUser.setImageUrl(fileUrl1);
        chartViewsUser.setLargeScreenUrl(fileUrl2);
        chartViewsUser.setViewValue(chartViewsUser.getViewValue());
        boolean result = chartViewsUserService.save(chartViewsUser);
        if (result) {
            return AjaxResult.success(chartViewsUser.getId());
        }
        return AjaxResult.error();
    }


    /**
     * 保存大屏照片到  OSS
     */
    @PostMapping("/user/add/photoToOSS")
    @Transactional
    public AjaxResult addFile(@RequestPart(value = "file", required = false) MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        // 获取当前日期并格式化为 "yyMMdd"
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        // 生成随机数字并进行 MD5 加密
        String randomNumber = String.valueOf(RandomUtils.nextInt(0, 100000));
        String md5FileName = generateMD5(randomNumber);
        // 构造文件路径：chartCover/241209/md5(XXXX).png
        String fileName = "largeScreen/" + datePrefix + "/" + md5FileName + ".png";

        String fileUrl = null;
        OSS ossClient = null;
        try {

            ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

            // 上传文件
            ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(bytes));
            // 设置文件权限为公共读
            ossClient.setObjectAcl(ossConfig.getBucketName(), fileName, CannedAccessControlList.PublicRead);

            // 构造文件访问 URL
            if (ossConfig.getCustomDomain() != null && !ossConfig.getCustomDomain().isEmpty()) {
                fileUrl = ossConfig.getCustomDomain() + fileName;
            } else {
                fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + fileName;
            }
        } catch (OSSException e) {
            log.error("文件1上传到 OSS 失败", e);
            return AjaxResult.error("文件上传失败");
        } catch (ClientException e) {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return AjaxResult.success("操作成功", fileUrl);
    }


    @ApiOperation("数字大屏：新增")
    @PostMapping("/user/add/largeScreen")
    @Transactional
    public AjaxResult largeScreen(@RequestBody ChartViewsUser chartViewsUser) {
        // 参数校验
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写大屏名称");
        }
        if (StringUtils.isEmpty(chartViewsUser.getImageUrl())) {
            return AjaxResult.error("imageUrl为空，请重试");
        }
        if (StringUtils.isEmpty(chartViewsUser.getLargeScreenUrl())) {
            return AjaxResult.error("largeScreenUrl为空，请重试");
        }

        if (StringUtils.isEmpty(chartViewsUser.getViewValue())) {
            return AjaxResult.error("viewValue为空，请重试");
        }

        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()));
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("大屏名称重复");
        }
        chartViewsUser.setUserId(SecurityUtils.getUserId());
        chartViewsUser.setImageUrl(chartViewsUser.getImageUrl());
        chartViewsUser.setLargeScreenUrl(chartViewsUser.getLargeScreenUrl());
        chartViewsUser.setViewValue(chartViewsUser.getViewValue());
        boolean result = false;
        try {
            result = chartViewsUserService.save(chartViewsUser);
        } catch (Exception e) {
            log.error("大屏保存失败");
            throw new RuntimeException(e);
        }
        if (result) {
            return AjaxResult.success(chartViewsUser.getId());
        }
        return AjaxResult.error();
    }


    /**
     * 解码Base64字符串并移除前缀
     *
     * @param base64Image Base64编码的图像字符串
     * @return 解码后的字节数组
     * @throws IllegalArgumentException 如果Base64编码无效
     */
    private byte[] decodeBase64Image(String base64Image) {
        if (base64Image.startsWith("data:image/png;base64,")) {
            base64Image = base64Image.substring("data:image/png;base64,".length());
        }
        return Base64.getDecoder().decode(base64Image);
    }

    // 生成 MD5 值
    private String generateMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b)); // 转换为十六进制字符串
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5 生成失败", e);
            return "";
        }
    }


    @ApiOperation("数字大屏：修改")
    @PostMapping("/user/edit")
    @Transactional
    public AjaxResult edit(@RequestBody ChartViewsUser chartViewsUser, MultipartFile file) {
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写图表名称");
        }
        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .ne(ChartViewsUser::getId, chartViewsUser.getId()).eq(ChartViewsUser::getUserId, SecurityUtils.getUserId()));
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("图表名称重复");
        }
        if (!ObjectUtils.isEmpty(chartViewsUser.getBase64Data())) {
            String base64Image = chartViewsUser.getBase64Data();
            // 将base64编码的图片字符串解码
            byte[] decodedBytes = Base64.getDecoder().decode(base64Image);
            // 获取图片类型
            String imageType = base64Image.substring(base64Image.indexOf("/") + 1, base64Image.indexOf(";"));

            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            String newFileName = viewPhotoUrl + uuid + "." + imageType;

            String photo = photoUrl + uuid + "." + imageType;

            // 将解码后的字节数组保存为图片文件
            try (FileOutputStream fos = new FileOutputStream(newFileName)) {
                fos.write(decodedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String viewValue = chartViewsUser.getViewValue();
            JSONObject jsonObject = JSON.parseObject(viewValue);
            jsonObject.put("base64Data", photo);
            chartViewsUser.setViewValue(JSON.toJSONString(jsonObject));
        }
        return AjaxResult.success(chartViewsUserService.saveOrUpdate(chartViewsUser));
    }


    @ApiOperation("数字大屏：根据id获取单个图表详情")
    @GetMapping("/user/getInfo")
    public AjaxResult getInfo(ChartViewsUser chartViewsUser) {
        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getId, chartViewsUser.getId()));
        return AjaxResult.success(one);
    }

    @ApiOperation("数字大屏：根据id删除（支持批量）")
    @PostMapping("/user/del")
    @Transactional
    public AjaxResult del(@RequestBody ChartViewsUser chartViewsUser) {
        return AjaxResult.success(chartViewsUserService.removeByIds(chartViewsUser.getIds()));
    }


    /*
        @PostMapping("checkout")
        public AjaxResult checkout(@RequestBody ChartViewsDTO chartViewsDTO) {
            Long id = chartViewsDTO.getId();
            String password = chartViewsDTO.getPassword();
            LambdaQueryWrapper<ChartViewsUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChartViewsUser::getId, id);
            ChartViewsUser user = chartViewsUserService.getOne(wrapper);
            if (user == null) {
                return AjaxResult.error(570, "未查询到该大屏信息");
            }

            if (user.getAccessCheck() == 1) {
                // 获取存储的哈希密码
                String hashedPassword = user.getPassword();

                // 使用 BCrypt 进行密码验证
                if (BCrypt.checkpw(password, hashedPassword)) {
                    // 如果匹配，表示验证成功
                    String str = IdUtils.generateRandomNumber();

                    String token = generateMD5(str);

                    return AjaxResult.success("验证成功", token);
                } else {
                    // 如果不匹配，返回错误信息
                    return AjaxResult.error(571, "密码错误");
                }

            }else {

                // 如果匹配，表示验证成功
                String str = IdUtils.generateRandomNumber();

                String token = generateMD5(str);
                return AjaxResult.success("验证成功", token);
            }


        }
    */

    @Autowired
    private RedisCache redisCache;


/*
    @PostMapping("checkout")
    public AjaxResult checkout(@RequestBody ChartViewsDTO chartViewsDTO) {
        Long id = chartViewsDTO.getId();
        String password = chartViewsDTO.getPassword();
        // 将 Long id 转换为 String
        String redisKey = Constants.TOKELARGESCREE  + String.valueOf(id);



        // 创建查询条件
        LambdaQueryWrapper<ChartViewsUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChartViewsUser::getId, id);

        // 执行查询，获取单个结果（假设 ID 是唯一的）
        ChartViewsUser user = chartViewsUserService.getOne(wrapper);
        if (user == null) {
            return AjaxResult.error(570, "未查询到该大屏信息");
        }

        // 检查访问校验是否开启
        if (user.getAccessCheck() == 1) {
            // 获取存储的哈希密码
            String storedHashedPassword = user.getPassword();

            // 使用 MD5 进行密码验证
            String inputHashedPassword = hashPassword(password);
            if (inputHashedPassword.equals(storedHashedPassword)) {
                // 如果匹配，表示验证成功，生成并返回 token
                String number = IdUtils.generateRandomNumber();
                String token = hashPassword(number);

                redisCache.setCacheObject(redisKey, token, 24, TimeUnit.HOURS);

                AjaxResult ajax = AjaxResult.success();
                ajax.put(Constants.TOKELARGESCREE, token);

                return ajax;
            } else {
                // 如果不匹配，返回错误信息
                return AjaxResult.error(571, "密码错误");
            }




        } else {
            String number = IdUtils.generateRandomNumber();
            String token = hashPassword(number);

            String redisKey = Constants.TOKELARGESCREE  + String.valueOf(id);
            redisCache.setCacheObject(redisKey, token, 24, TimeUnit.HOURS);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKELARGESCREE, token);

            return ajax;
        }
    }
*/


    //@PostMapping("checkout")
    public AjaxResult checkoutBefer(@RequestBody ChartViewsDTO chartViewsDTO) {
        Long id = chartViewsDTO.getId();
        String password = chartViewsDTO.getPassword();

        // 将 Long id 转换为 String 并构建 Redis 键
        String redisKey = Constants.TOKELARGESCREE + "_" + String.valueOf(id);

        // 先尝试从 Redis 中获取 token
        String token = redisCache.getCacheObject(redisKey);

        if (token != null) {

            // 如果 Redis 中存在 token，直接返回
            AjaxResult ajax = AjaxResult.success();
            Map<String, Object> data = new HashMap<>();
            data.put(Constants.TOKELARGESCREE, token);
            ajax.put(AjaxResult.DATA_TAG, data); // 将token放在data里面
            return ajax;
        }

        // 如果 Redis 中没有找到 token 或者 token 已过期，则继续后续逻辑

        // 创建查询条件
        LambdaQueryWrapper<ChartViewsUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChartViewsUser::getId, id);

        // 执行查询，获取单个结果（假设 ID 是唯一的）
        ChartViewsUser user = chartViewsUserService.getOne(wrapper);
        if (user == null) {
            return AjaxResult.error(570, "未查询到该大屏信息");
        }

        // 检查访问校验是否开启并进行密码验证
        if (user.getAccessCheck() == 1) {
            // 获取存储的哈希密码
            String storedHashedPassword = user.getPassword();

            // 使用 MD5 进行密码验证
            String inputHashedPassword = hashPassword(password);
            if (!inputHashedPassword.equals(storedHashedPassword)) {
                // 如果不匹配，返回错误信息
                return AjaxResult.error(571, "密码错误");
            }
        }

        // 生成新的 token
        String number = IdUtils.generateRandomNumber();
        token = hashPassword(number);

        // 将新生成的 token 存入 Redis，并设置过期时间为 24 小时
        redisCache.setCacheObject(redisKey, token, 24, TimeUnit.HOURS);

        // 返回成功响应并包含 token
//        AjaxResult ajax = AjaxResult.success();
//        ajax.put(Constants.TOKELARGESCREE, token);
//
//        return ajax;
        AjaxResult ajax = AjaxResult.success();
        Map<String, Object> data = new HashMap<>();
        data.put(Constants.TOKELARGESCREE, token);
        ajax.put(AjaxResult.DATA_TAG, data); // 将token放在data里面
        return ajax;
    }


    @PostMapping("checkout")
    public AjaxResult checkout(@RequestBody ChartViewsDTO chartViewsDTO) {
        Long id = chartViewsDTO.getId();
        String password = chartViewsDTO.getPassword();
        // 创建查询条件
        LambdaQueryWrapper<ChartViewsUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChartViewsUser::getId, id);
        // 执行查询，获取单个结果（假设 ID 是唯一的）
        ChartViewsUser user = chartViewsUserService.getOne(wrapper);
        if (user == null) {
            return AjaxResult.error(404, "未查询到该大屏信息");
        }
        // 获取存储的哈希密码
        String storePassword = user.getPassword();
        if (!password.equals(storePassword)) {
            // 如果不匹配，返回错误信息
            return AjaxResult.error(571, "密码错误");
        }

        // 生成新的 token
        String number = IdUtils.generateRandomNumber();
        String token = hashPassword(number);
       // String tokens = "tokens:" + token;
        String tokens = CacheConstants.LARGE_TOKEN_KEY + token;
        String tokenValue = String.valueOf(id); // 将 Long 转为 String
        // 将新生成的 token 存入 Redis，并设置过期时间为 24 小时
        redisCache.setCacheObject(tokens, tokenValue, 24, TimeUnit.HOURS);

        AjaxResult ajax = AjaxResult.success();
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        ajax.put(AjaxResult.DATA_TAG, data); // 将token放在data里面
        return ajax;
    }


    //根据id查询token是否过期

    @GetMapping("queryTokenById")
    public AjaxResult queryTokenById(Long id, String token) {

        //String tokens = "tokens:" + token;
        String tokens = CacheConstants.LARGE_TOKEN_KEY + token;

        String token1 = redisCache.getCacheObject(tokens);
        if (StringUtils.isEmpty(token1)) {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("token", "");
            map.put("IsExpireds", "0");
            return AjaxResult.success(map);
        } else {
            HashMap<Object, Object> map = new HashMap<>();
            map.put("token", token1);
            map.put("IsExpireds", "1");
            return AjaxResult.success(map);
        }


    }


    // 方法用于将字符串转换为MD5哈希
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(password.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


}
